package com.qf.dao.impl;

import com.qf.dao.GoodsDao;
import com.qf.pojo.Goods;
import com.qf.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 29125
 * @version V1.0
 * @Project java2203
 * @Package com.qf.dao.impl
 * @Description:
 * @Date 2022/5/25 11:32
 */
public class GoodsDaoImpl implements GoodsDao {
    //创建dbUtils工具类
    private QueryRunner queryRunner= new QueryRunner(DBUtil.getDataSource());
    //商品查询所有
    @Override
    public List<Goods> findGoodsAll() {
        //左连接   表连接语句
        String sql=" select a.*, b.name typeName from tb_goods a "+" left join tb_goods_type b on a.tid=b.id ";
        try {
            List<Goods> list=queryRunner.query(sql,new BeanListHandler<Goods>(Goods.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //根据ID查找商品
    @Override
    public Goods findById(Integer id) {
        String sql=" select * from tb_goods where id=? ";
        try {
            Goods goods=queryRunner.query(sql,new BeanHandler<Goods>(Goods.class));
            return goods;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //添加商品
    @Override
    public void insertGoods(Goods goods) {
        String sql=" insert into tb_goods (name, pubdate, picture, price, star, intro, tid) value (?, ?, ?, ?, ?, ?, ?) ";
        try {
            queryRunner.update(sql,goods.getName(),goods.getPubdate(),goods.getPicture(),goods.getPrice(),goods.getStar(),goods.getIntro(),goods.getTid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
